class Matrix2 {

    constructor() {

        Object.defineProperty(this, 'isMatrix2', {value: true});

        this.elements = [
            1, 0,
            0, 1
        ]
    }

    set(n11, n12, n21, n22) {

        const te = this.elements;

        te[0] = n11;
        te[1] = n21;
        te[2] = n12;
        te[3] = n22;

        return this;
    }

    identity() {

        this.set(1, 0, 0, 1);

        return this;
    }

    multiply(m) {

        return this.multiplyMatrices(m, this);
    }

    premultiply(m) {

        return this.multiplyMatrices(this, m);
    }

    multiplyMatrices(a, b) {

        const ae = a.elements;
        const be = b.elements;
        let te = this.elements;

        const a11 = ae[0], a12 = ae[2];
        const a21 = ae[1], a22 = ae[3];

        const b11 = be[0], b12 = be[2];
        const b21 = be[1], b22 = be[3];

        te[0] = a11 * b11 + a12 * b21;
        te[2] = a11 * b12 + a12 * b22;

        te[1] = a21 * b11 + a22 * b21;
        te[3] = a21 * b12 + a22 * b22;

        return this;
    }

    determinant() {

        const te = this.elements;

        return te[0] * te[3] - te[1] * te[2];
    }

    getInverse(m) {

        const me = m.elements;
        const te = this.elements;

        const det = m.determinant();

        if (det === 0) return this.set(0, 0, 0, 0);

        const detInv = 1 / det;

        te[0] = me[3] * detInv;
        te[1] = - me[1] * detInv;
        te[2] = - me[2] * detInv;
        te[3] = me[0] * detInv;

        return this;
    }
}

export default Matrix2